package cn.web.web_module.service.impl;

import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.util.DateUtils;
import cn.web.web_module.entity.*;
import cn.web.web_module.mapper.BusinessDataMapper;
import cn.web.web_module.mapper.WithdrawRechargeInfoMapper;
import cn.web.web_module.service.BusinessDataService;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;


import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 张松
 * @Description:
 * @Date: Created in 15:29 2020/8/17
 * @Modified By:
 */
@Service
public class BusinessDataServiceImpl implements BusinessDataService {

    @Resource
    private BusinessDataMapper businessDataMapper;

    @Resource
    private orderItemMapper orderItemMapper;

    @Resource
    private infoMapper infoMapper;

    @Resource
    private earningsMapper earningsMapper;

    @Resource
    private accountMapper accountMapper;

    @Resource
    private WithdrawRechargeInfoMapper withdrawRechargeInfoMapper;


    @Resource
    private horsemanMapper horsemanMapper;

    @Resource
    private orderMapper orderMapper;


    @Resource
    private rechargeMapper rechargeMapper;


    @Resource
    private withdrawMapper withdrawMapper;

    @Resource
    private packageOrderMapper packageOrderMapper;


    @Resource
    private packageOrderItemMapper packageOrderItemMapper;







    @Override
    public List<MonthData> EveryMonthAddUser() {
        return businessDataMapper.EveryMonthAddUser();
    }

    @Override
    public List<MonthData> AllUserData() {
        return businessDataMapper.AllUserData();
    }

    @Override
    public List<MonthData> EveryMonthAddOrder() {
        return businessDataMapper.EveryMonthAddOrder();
    }

    @Override
    public List<MonthData> AllOrderData() {
        return businessDataMapper.AllOrderData();
    }

    @Override
    public List<MonthData> EveryMonthWeight() {
        return businessDataMapper.EveryMonthWeight();
    }

    @Override
    public List<MonthData> AllWeight() {
        return businessDataMapper.AllWeight();
    }

    @Override
    public List<MonthData> EvenMothProduct() {
        return businessDataMapper.EvenMothProduct();
    }

    @Override
    public List<MonthData> AverageWeight() {
        return businessDataMapper.AverageWeight();
    }

    @Override
    public List<MonthData> UserEarning() {
        return businessDataMapper.UserEarning();
    }


    @Override
    public List<MonthData> EvenMonthAvgWeight() {
        List<MonthData> list = new ArrayList();
        List<MonthData> EveryMonthAddOrder = businessDataMapper.EveryMonthAddOrder();
        List<MonthData> EveryMonthWeight = businessDataMapper.EveryMonthWeight();
        for (int i=0;i<EveryMonthAddOrder.size();i++){
            Double EveryMonthOrder = EveryMonthAddOrder.get(i).getMoneyOrWeight(); //获取每月订单量
            Double EveryMonthOrderWeight = EveryMonthWeight.get(i).getMoneyOrWeight(); //获取每月收货重量
            DecimalFormat df = new DecimalFormat("0.00"); //把double转换成两位数
            String EvenMonthAvgWeight = df.format(EveryMonthOrderWeight / EveryMonthOrder); //每月订单量除以每月收货重量=每月平均每单重量
            MonthData monthData = new MonthData(); //接收对象
            monthData.setMonth(EveryMonthAddOrder.get(i).getMonth());
            monthData.setMoneyOrWeight(EveryMonthOrder);
            monthData.setProduct(EvenMonthAvgWeight);
            list.add(monthData);
        }
        return list;
    }

    @Override
    public List<order> horesemanEvenDayEarnings() {
        List<order> orders = businessDataMapper.horesemanEvenDayEarnings();
        List<earnings> earnings = businessDataMapper.horsemanSaleMoney(getEvenDayDateString()+"%");
        for (order order : orders) {
            order.setPayForecastMoney(0.0);
            for (earnings earnings1:earnings){
                if (order.getHorsemanAccount().equals(earnings1.getOpenid())){
                    order.setPayForecastMoney(earnings1.getNum());
                }
            }
        }
        return orders;
    }

    /**
     *
     * @Description:  获取昨日时间字符串
     *
     * @auther: 张松
     * @date: 8:56 2020/9/10
     * @param: []
     * @return: java.lang.String
     *
     */
    public  String getEvenDayDateString(){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DAY_OF_MONTH,-1);
        Date date = c.getTime();
        SimpleDateFormat simpleDateFormatYear = new SimpleDateFormat("yyyy");
        SimpleDateFormat simpleDateFormatMonth = new SimpleDateFormat("MM");
        SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("dd");
        String year = simpleDateFormatYear.format(date);
        String month = simpleDateFormatMonth.format(date);
        String day = simpleDateFormatDay.format(date);
        return year+month+day;
    }

    /**
     *
     * @Description: 查看用户上三次成交价格
     *
     * @auther: 张松
     * @date: 8:59 2020/9/3
     * @param: [openid]
     * @return: java.util.List<cn.itcast.pojo.orderItem>
     *
     */
    @Override
    public List<orderItem> selectPrice(String openid) {
        List<orderItem> orders = orderItemMapper.selectPrice(openid);
        for (orderItem orderitem : orders) {
            String orderImg = orderitem.getItemImg();
            if (StringUtils.isBlank(orderImg)){
                orderitem.setItemImg("暂无图片");
                continue;
            }
            String[] split = orderImg.split(",");
            String s = split[1];
            orderitem.setItemImg(s);

        }
        return orders;
    }



    /**
     *
     * @Description: 根据日期查找骑手的经营数据
     *
     * @auther: 张松
     * @date: 18:03 2020/9/3
     * @param: [timeDate]
     * @return: void
     *
     */
    @Override
    public Map<String, Object> selectHorsemanData(Date timeDate) {
        Map <String,String> date = new HashMap<>();
        Map<String, Object> selectHorsemanData= new HashMap<>();
        SimpleDateFormat dateYear = new SimpleDateFormat("yyyy");
        SimpleDateFormat dateMonth = new SimpleDateFormat("MM");
        String year = dateYear.format(timeDate);
        String month = dateMonth.format(timeDate);
        date.put("year",year);
        date.put("month",month);
        List<info> infos = selectHorsemanWithdrew(date);  //查找某个时间段骑手的提现记录
        List<earnings> horsemanRecharge = selectHorsemanRecharge(year + month); //查找骑手的充值记录
        List<account> accounts = selectHorsemanAccount(); //查找骑手的账户余额
        List<earnings> horsemanEarning = selectHorsemanEarning(year + month); //查找骑手的收货价格
        List<earnings> horsemanRecycleMoney = selectHorsemanRecycleMoney(year + month);//骑手回收出售价格
        selectHorsemanData.put("infos",infos);
        selectHorsemanData.put("horsemanRecharge",horsemanRecharge);
        selectHorsemanData.put("accounts",accounts);
        selectHorsemanData.put("horsemanEarning",horsemanEarning);
        selectHorsemanData.put("horsemanRecycleMoney",horsemanRecycleMoney);
        return selectHorsemanData;
    }

    /**
     *
     * @Description: 查看公司昨日收入状况
     *
     * @auther: 张松
     * @date: 19:11 2020/9/10
     * @param: []
     * @return: java.util.List<cn.itcast.pojo.orderItem>
     *
     */
    @Override
    public List<earnings> selectCompanyDayEarning() {
        String source;
        Double num=0.0;
        String earningsExplain;
        List<earnings> earnings = businessDataMapper.selectCompanyDayEarning(getEvenDayDateString()+"%");
        for (earnings earning : earnings) {
            if (earning.getSource().equals("骑手支付")){
                source = earning.getSource();
            }else if(earning.getNum().equals("")){

            }
            num = earning.getNum();
            earningsExplain = earning.getEarningsExplain();
        }
        return earnings;
    }

    @Override
    public Integer selectHorsemanTodayAmount(String openId) {
        Integer integer = orderItemMapper.selectHorsemanTodayAmount(openId);
        if (integer==null){
            return 0;
        }
        return integer;
    }


    @Override
    public Integer selectHorsemanYesterdayAmount(String openId) {
        Integer integer = orderItemMapper.selectHorsemanYesterdayAmount(openId);
        if (integer==null){
            return 0;
        }
        return integer;
    }

    @Override
    public PageInfo selectHorsemanDetailedRecord(Map<String, String> parameters) {
        PageHelper.startPage(Integer.parseInt(parameters.get("page")),Integer.parseInt(parameters.get("pageSize")));
        List<HorsemanDetailedRecord> horsemanDetailedRecords = businessDataMapper.selectHorsemanDetailedRecord(parameters);
        PageInfo page = new PageInfo(horsemanDetailedRecords);
        List<HorsemanDetailedRecord> list = page.getList();
        for (HorsemanDetailedRecord horsemanDetailedRecord : list) {
            Integer orderId = horsemanDetailedRecord.getOrderId();
            WithdrawRechargeInfo withdrawRechargeInfo = withdrawRechargeInfoMapper.selectOrderId(orderId);
            if (withdrawRechargeInfo==null){
                continue;
            }
            if (withdrawRechargeInfo.getWithdrawMoney()!=null){
                horsemanDetailedRecord.setHorsemanWithdraw(withdrawRechargeInfo.getWithdrawMoney().doubleValue());
            }else {
                horsemanDetailedRecord.setHorsemanWithdraw(0.0);
            }
            if (withdrawRechargeInfo.getRechargeMoney()!=null){
                horsemanDetailedRecord.setHorsemanRecharge(withdrawRechargeInfo.getRechargeMoney().doubleValue());
            }else {
                horsemanDetailedRecord.setHorsemanRecharge(0.0);
            }
            if (StringUtils.isNotBlank(withdrawRechargeInfo.getRechargeNumber())){
                horsemanDetailedRecord.setRechargeNumber(withdrawRechargeInfo.getRechargeNumber());
            }else {
                horsemanDetailedRecord.setRechargeNumber(0+"");
            }
            if (withdrawRechargeInfo.getWithdrawId()!=null){
                horsemanDetailedRecord.setWithdrawNumber(withdrawRechargeInfo.getWithdrawId().toString());
            }else {
                horsemanDetailedRecord.setWithdrawNumber(0+"");
            }
            if (withdrawRechargeInfo.getPackageOrderId()!=null){
                horsemanDetailedRecord.setPackageOrderId(withdrawRechargeInfo.getPackageOrderId());
            }else {
                horsemanDetailedRecord.setPackageOrderId(0);
            }if (withdrawRechargeInfo.getPackageOrderMoney()!=null){
                horsemanDetailedRecord.setPackageOrderMoney(withdrawRechargeInfo.getPackageOrderMoney().doubleValue());
            }

        }
        return page;
    }


    /**
     *
     * @Description: 查找某个时间段骑手的提现记录
     *
     * @auther: 张松
     * @date: 11:40 2020/9/4
     * @param: [date]
     * @return: java.util.List<cn.itcast.pojo.info>
     *
     */
    List<info> selectHorsemanWithdrew(Map <String,String> date){
        List<info> infos = infoMapper.selectHorsemanWithdrew(date);
        return infos;
    }

    /**
     *
     * @Description:  查找骑手的充值记录
     *
     * @auther: 张松
     * @date: 18:18 2020/9/7
     * @param: []
     * @return: java.util.List<cn.itcast.pojo.earnings>
     *
     */
    List<earnings> selectHorsemanRecharge(String date){
        List<earnings> earnings = earningsMapper.selectHorsemanRecharge(date + "%");
        return earnings;
    }

    /**
     *
     * @Description: 查找骑手的账户余额
     *
     * @auther: 张松
     * @date: 18:39 2020/9/7
     * @param: []
     * @return: java.util.List<cn.itcast.pojo.account>
     *
     */
    List<account> selectHorsemanAccount(){
        List<account> accounts = accountMapper.selectHorsemanAccount();
        return accounts;
    }


    /**
     *
     * @Description: 查找骑手的收货价格
     * 
     * @auther: 张松
     * @date: 18:45 2020/9/7
     * @param: []
     * @return: java.util.List
     *
     */
    List<earnings> selectHorsemanEarning(String date){
        List<earnings> horsemanEarning = earningsMapper.selectHorsemanEarning(date + "%");
        return horsemanEarning;
    }

    /**
     *
     * @Description: 骑手回收出售价格
     *
     * @auther: 张松
     * @date: 18:57 2020/9/7
     * @param: [date]
     * @return: java.util.List<cn.itcast.pojo.earnings>
     *
     */
    List<earnings>  selectHorsemanRecycleMoney(String date){
        List<earnings> horsemanRecycleMoney = earningsMapper.selectHorsemanRecycleMoney(date + "%");
        return horsemanRecycleMoney;
    }




    /**
     *
     * @Description: 查找全部骑手的姓名
     *
     * @auther: 张松
     * @date: 16:11 2021/3/10
     * @param: []
     * @return: java.util.List<java.lang.String>
     *
     */
    @Override
    public List<String> selectIncumbencyAllHorsemanName() {
        List<String> horsemanName = new ArrayList<>();
        List<horseman> horsemen = horsemanMapper.ifIsOpen();
        horsemen.forEach((v)->{
            horsemanName.add(v.getHorsemanName());
        });
        return horsemanName;
    }

    @Override
    public List<OrderInfoOV> selectHorsemanOrderId(Integer orderId) {
        List<order> orders = orderMapper.selectHorsemanOrderId(orderId);
        List<orderItem> orderIdItems = orderItemMapper.findOrderId(orderId);
        List<OrderInfoOV> OrderInfoOVs = new ArrayList<>();
        orderIdItems.forEach((v)->{
            OrderInfoOV orderInfoOV = new OrderInfoOV();
            orderInfoOV.setOrderTime(DateUtils.format(orders.get(0).getOrderTime()));
            orderInfoOV.setUserName(orders.get(0).getUserName());
            orderInfoOV.setUserArea(orders.get(0).getUserArea());
            orderInfoOV.setUserPhone(orders.get(0).getUserPhone());
            orderInfoOV.setHorsemanName(orders.get(0).getHorsemanName());
            orderInfoOV.setPayTime(DateUtils.format(orders.get(0).getPayTime()));
            orderInfoOV.setPayProductType(orders.get(0).getPayProductType());
            orderInfoOV.setProductType(v.getProductType());
            orderInfoOV.setFinallyWeight(v.getFinallyWeight());
            orderInfoOV.setUnitPrice(v.getUnitPrice());
            orderInfoOV.setAmount(v.getAmount());
            orderInfoOV.setOrderUnit(v.getUnit());
            orderInfoOV.setOrderSum(v.getSum());
            OrderInfoOVs.add(orderInfoOV);
        });
        return OrderInfoOVs;
    }

    @Override
    public List<RechargeInfoOV> selectHorsemanRechargeInfo(String rechargeNumber) {
        List<recharge> recharges = rechargeMapper.selectRechargeNumber(rechargeNumber);
        List<RechargeInfoOV> rechargeInfoOVS = new ArrayList<>();
        recharges.forEach((v)->{
            RechargeInfoOV rechargeInfoOV = new RechargeInfoOV();
            rechargeInfoOV.setRechargeId(v.getId());
            rechargeInfoOV.setName(v.getName());
            rechargeInfoOV.setPhone(v.getPhone());
            rechargeInfoOV.setRechargeTime(DateUtils.format(v.getRechargeTime()));
            rechargeInfoOV.setBillTime(DateUtils.format(v.getBillTime()));
            rechargeInfoOV.setRechargeSum(v.getRechargeSum());
            rechargeInfoOV.setRechargeNumber(v.getRechargeNumber());
            rechargeInfoOV.setPayType(v.getPayType());
            rechargeInfoOV.setPayState(v.getPayState());
            rechargeInfoOV.setBillState(v.getBillState());
            rechargeInfoOVS.add(rechargeInfoOV);
        });

        return rechargeInfoOVS;
    }

    @Override
    public List<WithdrawInfoOV> selectHorsemanWithdrawInfo(Integer withdrawId) {
        withdraw withdraw = withdrawMapper.selectByPrimaryKey(withdrawId);
        List<WithdrawInfoOV> withdrawInfoOVList = new ArrayList<>();
        WithdrawInfoOV withdrawInfoOV = new WithdrawInfoOV();
        withdrawInfoOV.setId(withdraw.getId());
        withdrawInfoOV.setName(withdraw.getName());
        withdrawInfoOV.setPhone(withdraw.getPhone());
        withdrawInfoOV.setNum(withdraw.getNum());
        withdrawInfoOV.setApplyTime(DateUtils.format(withdraw.getApplyTime()));
        withdrawInfoOV.setBillTime(DateUtils.format(withdraw.getApplyTime()));
        withdrawInfoOV.setState(withdraw.getState());
        withdrawInfoOV.setType(withdraw.getType());
        withdrawInfoOVList.add(withdrawInfoOV);
        return withdrawInfoOVList;
    }

    @Override
    public List<PackageOrderInfoOV> selectHorsemanPackageOrderId(Integer packageOrderId) {
        packageOrder packageOrder = packageOrderMapper.selectByPrimaryKey(packageOrderId);
        List<packageOrderItem> packageOrderItems = packageOrderItemMapper.selectPackageOrderId(packageOrder.getId());
        List<PackageOrderInfoOV> packageOrderInfoOVS = new ArrayList<>();
        packageOrderItems.forEach((v)->{
            PackageOrderInfoOV packageOrderInfoOV = new PackageOrderInfoOV();
            packageOrderInfoOV.setId(packageOrder.getId());
            packageOrderInfoOV.setOldIds(packageOrder.getOldIds());
            packageOrderInfoOV.setOrderTime(DateUtils.format(packageOrder.getOrderTime()));
            packageOrderInfoOV.setHorsemanName(packageOrder.getHorsemanName());
            packageOrderInfoOV.setProductType(packageOrder.getProductType());
            packageOrderInfoOV.setRecycleName(packageOrder.getRecycleName());
            packageOrderInfoOV.setRecycleNumber(packageOrder.getRecycleNumber());
            packageOrderInfoOV.setPayTime(DateUtils.format(packageOrder.getPayTime()));
            packageOrderInfoOV.setRecycleWeigh(v.getRecycleWeigh());
            packageOrderInfoOV.setSumRecycle(v.getSumRecycle());
            packageOrderInfoOV.setMeasure(v.getMeasure());
            packageOrderInfoOVS.add(packageOrderInfoOV);
        });

        return packageOrderInfoOVS;
    }

    @Override
    public List<HorsemanDetailedRecord> downloadHorsemandetailedRecordExcel(Map<String, String> parameters) {
        PageInfo pageInfo = selectHorsemanDetailedRecord(parameters);
        //        String fileName = "C:\\Users\\Administrator\\Downloads\\simpleWrite" + System.currentTimeMillis() + ".xlsx";
//        EasyExcel.write(fileName, HorsemanDetailedRecord.class).sheet("模板").doWrite(list);
        return (List<HorsemanDetailedRecord>) pageInfo.getList();
    }

    @Override
    public List<packageOrderItem> horsemanEvenDayPackageOrder() {
        List<packageOrderItem> HorsemanEvenDayPackageOrderList=packageOrderItemMapper.horsemanEvenDayPackageOrder();
        return HorsemanEvenDayPackageOrderList;
    }

    @Override
    public List<HorsemanContrast> horsemanContrast() {
        List<HorsemanContrast> horsemanContrasts = new ArrayList<>();
        List<horseman> horsemens = horsemanMapper.ifIsOpen();
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.DATE,-1);
        Date time = calendar.getTime();
        DateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd");
        String date = dateFormat.format(time);
        for (horseman horsemen : horsemens) {
            HorsemanContrast horsemanContrast = new HorsemanContrast();
            String horsemanOpenId = horsemen.getOpenId();
            List<order> orders = orderMapper.selectHorsemanReceiptMoney(horsemanOpenId);
            if (orders.get(0)==null){
                continue;
            }
            List<packageOrder> packageOrders = packageOrderMapper.selectHorsemanSaleMoney(horsemanOpenId);
            if (packageOrders.get(0)==null){
                continue;
            }
            horsemanContrast.setEveryDay(date);
            horsemanContrast.setHorsemanName(horsemen.getHorsemanName());
            horsemanContrast.setHorsemanNumber(horsemen.getHorsemanIdNumber());
            horsemanContrast.setCity(horsemen.getCity());
            horsemanContrast.setProvince(horsemen.getProvince());
            horsemanContrast.setArea(horsemen.getHorsemanArea());
            horsemanContrast.setMoneyError(BigDecimal.valueOf(packageOrders.get(0).getOrderSumHorseman()-Double.parseDouble(orders.get(0).getPayForecastWeight())).setScale(2,BigDecimal.ROUND_DOWN));
            horsemanContrast.setEarning(BigDecimal.valueOf(packageOrders.get(0).getOrderSumRecycle()-orders.get(0).getPayOrderMoney()).setScale(2,BigDecimal.ROUND_DOWN));
            horsemanContrasts.add(horsemanContrast);
        }
        return horsemanContrasts;
    }


}
